// wx://form-field
// 使自定义组件有类似于表单控件的行为。 form 组件可以识别这些自定义组件，并在 submit 事件中返回组件的字段名及其对应字段值

import {
  axValidator
} from '../../components/ax-validator';

module.exports = Behavior({
  behaviors: ['wx://form-field'],

  properties: {
    /** 之所以将所有信息以对象的方式传入，是为了后面的数据验证 */
    props: {
      type: Object,
      observer(props) {
        if (props.defaultValue !== undefined && props.value === undefined) {
          props.value = props.defaultValue;
        }
        if (props.value === undefined) {
          props.value = ''
        }
        this.setData({
          ...this.data, //默认值
          placeholder: props.placeholder || '请输入' + props.label, //默认值
          ...props, //新值
        });
      }
    },
    value: {
      type: null,
      value: null,
      async observer(v) {
        const d = this.data;
        if (v) {
          await axValidator(d, v);
          this.setData({
            ...d,
          });
        }
      }
    },
    placeholder: String,
    name: String,
    axvalue: null,
  },

  data: {
    axvalue: '',
    value: '',
    required: false,
  },

  created: function () { },

  attached: function () { },

  ready: function () { },

  methods: {
    onChange: async function (e) {
      const v = e.detail;
      const d = this.data;
      await axValidator(d, v);
      this.setData({
        ...d,
        axvalue: d.value,
      });
      //触发一次组件上原生bindchange
      this.triggerEvent('change', v, {});
    },
    onBlur: async function (e) {
      const v = e.detail.value;
      const d = this.data;
      await axValidator(d, v);
      this.setData({
        ...d,
        axvalue: d.value,
      });
      //触发一次组件上原生bindchange
      this.triggerEvent('change', v, {});
    }
  },

  observers: {},
})